package ThreadPoolnio1;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class nioText {
    public static void main(String[] args) {
        //IOTest();
        NIOTest();
    }

    private static void NIOTest() {
        long time1=System.currentTimeMillis();
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream("C:\\Users\\29659\\Desktop\\text.txt");
            out = new FileOutputStream("text1.txt");
            FileChannel channel = in.getChannel();
            FileChannel outchannel = out.getChannel();
            ByteBuffer buff = ByteBuffer.allocate(1024);
            int count = channel.read(buff);
            System.out.println("readcount:"+count);
            while (count != -1) {
                buff.flip();
                while (buff.hasRemaining()) {
                    System.out.print((char) buff.get());
                }
                buff.flip(); //见前表
                outchannel.write(buff);
                buff.compact();
                count = channel.read(buff);
            }
            System.out.println();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null)
                    in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            long time2=System.currentTimeMillis();
            System.out.println("NIO运行所需的时间"+(time2-time1));
        }
    }
    public static  void  IOTest(){
        long time1=System.currentTimeMillis();
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new BufferedInputStream(new FileInputStream("C:\\Users\\29659\\Desktop\\text.txt"));
            out = new BufferedOutputStream(new FileOutputStream("text2.txt"));
            byte [] buf = new byte[1024];
            int bytesRead = in.read(buf);

            while (bytesRead != -1){
                for(int i = 0 ; i < bytesRead ; i ++)
                    System.out.print((char)buf[i]);
                out.write(buf,0, bytesRead);
                out.flush();
                bytesRead  = in.read(buf);
            }

            System.out.println();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                if(in != null){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            long time2=System.currentTimeMillis();
            System.out.println("IO运行所需的时间"+(time2-time1));
        }

    }

}